// FileIndexer: Build in-memory index of files from common user dirs
const fs = require('fs')
const path = require('path')
const os = require('os')

function isHidden(name) {
  return name.startsWith('.')
}

function walk(dir, out, maxCount) {
  try {
    const entries = fs.readdirSync(dir, { withFileTypes: true })
    for (const entry of entries) {
      if (out.length >= maxCount) return
      const full = path.join(dir, entry.name)
      if (entry.isDirectory()) {
        // Skip hidden/system-like dirs
        if (!isHidden(entry.name)) walk(full, out, maxCount)
      } else {
        // filter temp/hidden
        const lower = entry.name.toLowerCase()
        if (isHidden(entry.name) || lower.endsWith('.tmp') || lower.startsWith('~$')) continue
        out.push(full)
      }
    }
  } catch (_) {}
}

function defaultDirs() {
  const home = os.homedir()
  return [
    path.join(home, 'Desktop'),
    path.join(home, 'Documents'),
    path.join(home, 'Downloads'),
  ]
}

class FileIndexer {
  constructor() {
    this.items = [] // { id,name,path,type:'file', lastModified }
  }

  buildIndex(customDirs = []) {
    const now = Date.now()
    const dirs = [...defaultDirs(), ...customDirs]
    const files = []
    for (const d of dirs) {
      walk(d, files, 10000) // cap to avoid excessive IO
    }

    const indexed = []
    for (const file of files) {
      let stat
      try { stat = fs.statSync(file) } catch (_) { continue }
      const name = path.basename(file)
      indexed.push({ id: file, name, path: file, type: 'file', lastModified: stat.mtimeMs || now })
    }

    this.items = indexed
    return this.items
  }

  getAll() { return this.items }
}

module.exports = { FileIndexer }
